import React, { useEffect, useState,useRef } from 'react'
import '../assets/css/swiper.scss'
export default function Swiper(props) {
    useEffect(() => {
        console.log('props', props.swiperdata);
        autoPlay()
    }, [])
    //定义一个状态数据，该数用来表示轮播图目前的下标位置
    let [current, setCurrent] = useState(0)
    let [timer,setTimer]=useState(0)
    const leftBtn=useRef()
    const rightBtn=useRef()
    //自动轮播的效果
    const autoPlay=()=>{
        //使用间隔定时器来完成
         let t=setInterval(() => {
            console.log('********自动轮播*************');
            if(props.swiperdata.length===current){
              current=0
            }
            setCurrent(current++)
          }, 2000)
          setTimer(t)
          leftBtn.current.style.display="none"
          rightBtn.current.style.display="none"
    }
    //停止播放
    const stopPlay=()=>{
        clearInterval(timer)
        leftBtn.current.style.display="block"
        rightBtn.current.style.display="block"
    }
    /*向上一页 */
    const prevPage=()=>{
       console.log('--------prevPage-----------');
       console.log('current',current);
       if(current==0){
         setCurrent(props.swiperdata.length-1)
       }else{
        setCurrent(--current)
       }
    }
    const nextPage=()=>{
        console.log('--------nextPage-----------');
        console.log('current',current);
        if(current===props.swiperdata.length-1){
            setCurrent(0)
        }else{
            setCurrent(++current)
        }
    }
    return (
        <div className='swiper-box' onMouseEnter={stopPlay} onMouseLeave={autoPlay}>
            <div className="swiper-images">
                {props.swiperdata.map(((item, index) => {
                    if (index === current) {
                        return <img src={item} key={index} />
                    }
                }))}
            </div>
            <ul className='dotList'>
                {
                    props.swiperdata.map((item,index)=>{
                        if(index===current){
                            return <li className='active' key={index}></li>
                        }else{
                            return <li  key={index}></li>
                        }
                    })
                }
            </ul>
            <div className='leftBtn' ref={leftBtn} onClick={prevPage}>&lt;</div>
            <div className='rightBtn' ref={rightBtn} onClick={nextPage}>&gt;</div>

        </div>
    )
}
